import 'dart:io';

import 'package:camera/camera.dart';
import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/widgets.dart' hide Action;
import 'package:image_picker_saver/image_picker_saver.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:path/path.dart' as Path;
import 'package:path_provider/path_provider.dart';
import 'package:www.znpigai.teacher/utils/nav.dart';
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';
import 'state.dart';

Effect<CameraState> buildEffect() {
  return combineEffects(<Object, Effect<CameraState>>{
    Lifecycle.initState: _onInit,
    CameraAction.onGallery: _onGallery,
    CameraAction.onTake: _onTake,
    CameraAction.onSave: _onSave,
    CameraAction.onDone: _onDone,
  });
}

void _onInit(Action action, Context<CameraState> ctx) async {
  var cameras = await availableCameras();
  var controller = CameraController(cameras[0], ResolutionPreset.medium);
  await controller.initialize();
  ctx.dispatch(CameraActionCreator.init(cameras[0], controller));
}

void _onGallery(Action action, Context<CameraState> ctx) async {
  try {
    var resultList = await MultiImagePicker.pickImages(
        maxImages: 300,
        enableCamera: true,
        selectedAssets: ctx.state.selected,
        cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
        materialOptions: MaterialOptions(
          actionBarColor: "#abcdef",
          actionBarTitle: "选择照片",
          allViewTitle: "All Photos",
          selectCircleStrokeColor: "#000000",
        ));

    if (resultList.length > 0) {
      // ctx.dispatch(CameraActionCreator.select(resultList));
      Navigator.of(ctx.context)
          .pushNamed(Nav.PRACTICE_EDIT, arguments: {'list': resultList});
    } else {
      Util.alert('请选择照片', ctx.context);
    }
  } catch (e) {
    print(e);
  }
}

void _onTake(Action action, Context<CameraState> ctx) async {
  try {
    // Construct the path where the image should be saved using the path
    // package.
    final path = Path.join(
      // Store the picture in the temp directory.
      // Find the temp directory using the `path_provider` plugin.
      (await getTemporaryDirectory()).path,
      '${DateTime.now()}.png',
    );

    // Attempt to take a picture and log where it's been saved.
    await ctx.state.controller.takePicture(path);
    // Util.alert(path.toString(), ctx.context);
    ctx.dispatch(CameraActionCreator.tmpPhoto(path));
  } catch (e) {
    // If an error occurs, log the error to the console.
    print(e);
  }
}

void _onSave(Action action, Context<CameraState> ctx) async {
  var photoData = await File(ctx.state.tmpPhoto).readAsBytes();
  var filePath = await ImagePickerSaver.saveFile(fileData: photoData);
  ctx.dispatch(CameraActionCreator.save(filePath));
  Util.alert('照片已保存', ctx.context);
}

void _onDone(Action action, Context<CameraState> ctx) async {
  if (ctx.state.selected.length == 0) {
    Util.showMsgDialog('无照片', '请先拍照再识别', ctx.context);
  } else {
    Navigator.of(ctx.context).pushNamed(Nav.PRACTICE_EDIT);
  }
}
